package com.sc.nft.consumer;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.meta.user.client.api.UserLogOffRecordClient;
import com.meta.user.client.message.MetaUserInfoMessage;
import com.meta.user.client.req.UserLogOffRecordReq;
import com.sc.nft.dao.IdcardInfoDao;
import com.sc.nft.dao.UserChainInfoDao;
import com.sc.nft.dao.UserInfoDao;
import com.sc.nft.dao.UserWalletDao;
import com.sc.nft.dto.UserEcologyPointsDao;
import com.sc.nft.entity.IdcardInfo;
import com.sc.nft.entity.UserInfo;
import com.sc.nft.enums.MessageTopic;
import com.sc.nft.helper.MessageQueueHelper;
import com.sc.nft.service.BlockChainTypeService;
import com.sc.nft.service.UserChainInfoService;
import com.sc.nft.service.UserRelevanceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;


/**
 * 用户中台拆分后同步数据消息者实现
 * <p>
 * 注：更新过程中只更新与原业务一致的字段，不作多余动作，故不能采用 BeanUtils.copyProperties(source, target); 这类工具类实现
 */
@Slf4j
@Component
@RequiredArgsConstructor
@RocketMQMessageListener(topic = "${app.rocketmq.topic.user}",
        consumerGroup = "${app.rocketmq.consumer.group.user_sync}",
        selectorExpression = "${app.rocketmq.tags.user_register}" +
                "||${app.rocketmq.tags.user_invite}" +
                "||${app.rocketmq.tags.user_update_info}" +
                "||${app.rocketmq.tags.user_update_password}" +
                "||${app.rocketmq.tags.user_reset_password}" +
                "||${app.rocketmq.tags.user_cancellation}")
public class UserSyncConsumer implements RocketMQListener<MetaUserInfoMessage> {

    private final UserInfoDao userInfoDao;
    private final BlockChainTypeService blockChainTypeService;
    private final UserWalletDao userWalletDao;
    private final UserChainInfoDao userChainInfoDao;
    private final UserEcologyPointsDao userEcologyPointsDao;
    private final UserChainInfoService userChainInfoService;
    private final UserRelevanceService userRelevanceService;
    private final MessageQueueHelper messageQueueHelper;
    private final IdcardInfoDao idcardInfoDao;
    private final UserLogOffRecordClient userLogOffRecordClient;

    @Override
    @Transactional
    public void onMessage(MetaUserInfoMessage message) {
        log.info("开始消费消息 action: {}, message: {}", message.getUserActionEnum(), message);
        doMessage(message);
        if (log.isDebugEnabled()) {
            log.debug("结束消费消息 action: {}, message: {}", message.getUserActionEnum(), message);
        }
    }

    private void doMessage(MetaUserInfoMessage message) {
        if (message.getUserActionEnum() == null) {
            log.warn("当前消息实体未指定 $userActionEnum 字段值");
            return;
        }
        switch (message.getUserActionEnum()) {
            case REGISTER:
//                register(message);
                break;
            case INVITE:
                invite(message);
                break;
            case CHANGE_BASIC_INFO:
                updateInfo(message);
                break;
            case CHANGE_PWD:
            case RESET_PWD:
                updatePwd(message);
                break;
            case CANCEL:
                cancel(message);
                break;
            default:
                log.warn("暂不支持的消息类型 action: {}", message.getUserActionEnum());
                break;
        }
    }

    private void cancel(MetaUserInfoMessage message) {
        // 注销用户
        UserInfo model = new UserInfo();
        model.setId(message.getId());
        model.setPwd(message.getPwd());
        model.setUserTel(message.getUserTel());
        model.setIsCancellation(message.getIsCancellation());
        userInfoDao.updateForSyncConsumer(model);

        IdcardInfo idcardInfo = idcardInfoDao.getByUserIdAndIsPass(message.getId());
        if (ObjectUtil.isNotNull(idcardInfo)) {
            idcardInfo.deleteById();

            UserLogOffRecordReq idCardRecord = new UserLogOffRecordReq();
            idCardRecord.setLogOffKey(idcardInfo.getCardId());
            idCardRecord.setReleaseTime(DateUtil.offsetMonth(DateTime.now(), 3));
            idCardRecord.setUserId(message.getId());
            userLogOffRecordClient.save(idCardRecord);
        }
    }

    private void updatePwd(MetaUserInfoMessage message) {
        UserInfo model = new UserInfo();
        model.setId(message.getId());
        model.setPwd(message.getPwd());
        userInfoDao.updateForSyncConsumer(model);
    }

    private void updateInfo(MetaUserInfoMessage message) {
        UserInfo model = new UserInfo();
        model.setId(message.getId());
        model.setNickName(message.getNickName());
        model.setAvatarImg(message.getAvatarImg());
        model.setBackGroundImg(message.getBackGroundImg());
        model.setBriefIntroduction(message.getBriefIntroduction());
        userInfoDao.updateForSyncConsumer(model);
    }

    private void invite(MetaUserInfoMessage message) {
        if (message.getRecommendUserId() == null) {
            return;
        }

        // 推荐人信息
        UserInfo recommendUserInfo = userInfoDao.getById(message.getRecommendUserId());
        if (Objects.isNull(recommendUserInfo)) {
            return;
        }

        UserInfo userInfo = new UserInfo();
        userInfo.setId(message.getId());
        userInfo.setInviteCode(message.getInviteCode());
        userInfo.setBindFlag(message.getBindFlag());
        userInfo.setRecommendUserId(message.getRecommendUserId());

        // 初始化用户邀请关系
        String recommendUserIdList = recommendUserInfo.getRecommendUserIdList();
        if (recommendUserIdList.equals("0") || StrUtil.isBlank(recommendUserIdList)) {
            userInfo.setRecommendUserIdList(recommendUserInfo.getId().toString());
        } else {
            userInfo.setRecommendUserIdList(recommendUserIdList + "," + recommendUserInfo.getId());
        }
        userInfoDao.updateForSyncConsumer(userInfo);

        // 注册的时候,一起生成树状的对应图标
        userRelevanceService.userInfoDataSynchronism(userInfo.getRecommendUserIdList(), userInfo.getUserTel(), userInfo.getId());
        messageQueueHelper.sendMessage(MessageTopic.USER_REGISTER, recommendUserInfo);
    }

//    private void register(MetaUserInfoMessage message) {
//        // 创建用户
//        UserInfo userInfo = new UserInfo();
//        // 同步字段
//        userInfo.setId(message.getId());    // ID系同步数值，不能使用自增
//        userInfo.setUserTel(message.getUserTel());
//        userInfo.setNickName(message.getNickName());
//        userInfo.setPwd(message.getPwd());
//        userInfo.setRecommendUserId(null == message.getRecommendUserId() ? 1L : message.getRecommendUserId());
//        userInfo.setUserUuid(message.getUserUuid());
//        userInfo.setInviteCode(message.getInviteCode());
//        // 默认字段
//        userInfo.setHoldToken(BigDecimal.ZERO);
//        userInfo.setIsFreeze(Boolean.FALSE);
//        userInfo.setIsSm(Boolean.FALSE);
//        userInfo.setIsCreator(Boolean.FALSE);
//        userInfo.setIsAddr(Boolean.FALSE);
//        userInfo.setIsUser(UserAccoutTypeEnum.USER_TEL.getCode());
//        userInfo.setIsValid(Boolean.FALSE);
//        userInfo.setIsThird(Boolean.TRUE);
//        userInfo.setOutSideKey(Long.toHexString(SystemClock.now() / 10) + RandomUtil.randomInt(0, 999));
//        userInfo.setSandWithdrawUuid(userInfo.getUserUuid());
//        userInfoDao.saveForSyncConsumer(userInfo);
//
//        // 邀请
//        if (StrUtil.isNotBlank(userInfo.getInviteCode())) {
//            invite(message);
//        }
//
//        // 注册后置处理 初始化钱包和地址
//        messageQueueHelper.sendMessage(MessageTopic.USER_REGISTER_INIT, userInfo);
//    }

}
